//待缩放原图的位置

const images = require('images')
const sharp = require('sharp');
const fs = require("fs")
const path = require('path')

const iconWidth = 180

//icon输出路径
let iconOutPathRoot = path.join(__dirname, 'icons');

let oneTpIconCnt = 165;
let arrayNames = ['1-165', '166-330'];
var resPath = path.join(__dirname, '../pngToWebp/doing')
let resArray = []
var rootDir = fs.readdirSync(resPath);
var handledidxFrom0 = 0
arrayNames.forEach((dir) => {
    deleteFileInDirectory(path.join(iconOutPathRoot, dir))
})
rootDir.forEach(function (file, idx) {
    let fullPath = path.join(resPath, file)
    var info = fs.statSync(fullPath)
    if (info.isDirectory()) {
    } else {
        if (isSupportExt(file)) {
            try {
                let fileNameWithoutExt = path.basename(fullPath, path.extname(fullPath));
                fileNameWithoutExt = "'" + fileNameWithoutExt + "'"
                handledidxFrom0++;
                let savePath = path.join(iconOutPathRoot + "/" + arrayNames[0], file)
                if (handledidxFrom0 >= 166)
                    savePath = path.join(iconOutPathRoot + "/" + arrayNames[1], file)
                // img.size(iconWidth).save(path.join(iconOutPathRoot + "/" + arrayNames[1], file), { 'quality': 95 })
                // img.size(iconWidth).save(path.join(iconOutPathRoot + "/" + arrayNames[0], file), { 'quality': 95 })
                sharp(fullPath)
                    .resize(180, 127)
                    .png({ quality: 95 })
                    .toFile(savePath).then(() => {
                        // console.log('图片已成功缩小并保存为', savePath);
                    })
                    .catch(err => {
                        console.error('处理图片时出错：', err);
                    });
                resArray.push(fileNameWithoutExt)
            } catch (e) {
                console.error(`Error processing file ${fullPath}:`, e);
            }
        }
    }
})
console.log(resArray.toString())
function isSupportExt(fileName) {
    let ext = path.extname(fileName)
    return ext === '.png' && fileName.indexOf('_b') == -1
}

function isSupportPixelSize(width) {
    return width >= 400
}

function deleteFileInDirectory(directoryPath) {
    // 清空目录中的文件
    let files = fs.readdirSync(directoryPath)
    files.forEach(file => {
        const filePath = path.join(directoryPath, file);
        fs.unlinkSync(filePath)
        console.log(`已删除: ${filePath}`);
    });
}

// let img = images()